/**
 * Copyright (c) 2011 Roundarch (www.roundarch.com)
 *
 * Author Joshua Jung
 *
 * ---
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.roundarch.flex.controls.intervals
{
    import com.roundarch.flex.controls.dateSliderClasses.DateSliderConst;
    import com.roundarch.flex.controls.graphControlInterfaces.IInterval;
    import com.roundarch.flex.controls.graphControlInterfaces.IIntervalCollection;
    import flash.events.Event;
    import flash.events.EventDispatcher;

    /**
     *
     * @author jjung
     */
    public class DateIntervalCollection extends IntervalCollectionBase
    {
        //---------------------------------------------------------------------
        //
        //  Properties
        //
        //---------------------------------------------------------------------
        //-----------------------------
        // dateStart
        //-----------------------------
        /**
         * @private
         */
        protected var _dateStart : Date = new Date(2000, 0, 1);

        [Bindable("dateStartChanged")]
        /**
         * The start of this interval collection. All values before this are not considered valid.
         *
         * @default null
         */
        public function get dateStart() : Date
        {
            return _dateStart;
        }

        /**
         * @private
         */
        public function set dateStart(value : Date) : void
        {
            if (value == _dateStart)
            {
                return;
            }

            _dateStart = value;

            dispatchEvent(new Event("dateStartChanged"));
            dispatchEvent(new Event("change"));
        }

        //-----------------------------
        // intervalType
        //-----------------------------
        /**
         * @private
         */
        protected var _intervalType : String = "day";

        [Bindable("intervalTypeChanged")]
        /**
         * The type of interval. Can be "day", "month", or "year"
         *
         * @default null
         */
        public function get intervalType() : String
        {
            return _intervalType;
        }

        /**
         * @private
         */
        public function set intervalType(value : String) : void
        {
            if (value == _intervalType)
            {
                return;
            }

            _intervalType = value;

            dispatchEvent(new Event("intervalTypeChanged"));
            dispatchEvent(new Event("change"));
        }

        //-----------------------------
        // intervalTypeCount
        //-----------------------------
        /**
         * @private
         *
         * Default interval length is 1 of whatever type is selected. See intervalType.
         */
        protected var _intervalTypeCount : Number = 1;

        [Bindable("intervalTypeCountChanged")]
        /**
         * The length of an interval between startDate and endDate, in milliseconds.
         *
         * Default interval length is one day.
         *
         * @default 60*60*24
         */
        public function get intervalTypeCount() : Number
        {
            return _intervalTypeCount;
        }

        /**
         * @private
         */
        public function set intervalTypeCount(value : Number) : void
        {
            if (value == _intervalTypeCount)
            {
                return;
            }

            _intervalTypeCount = value;

            dispatchEvent(new Event("intervalTypeCountChanged"));
            dispatchEvent(new Event("change"));
        }

        //-----------------------------
        // dateEnd
        //-----------------------------
        /**
         * @private
         */
        protected var _dateEnd : Date = new Date(2016, 0, 1);

        [Bindable("dateEndChanged")]
        /**
         * The end of this interval collection. All values after this are considered out of bounds and invalid.
         *
         * @default null
         */
        public function get dateEnd() : Date
        {
            return _dateEnd;
        }

        /**
         * @private
         */
        public function set dateEnd(value : Date) : void
        {
            if (value == _dateEnd)
            {
                return;
            }

            _dateEnd = value;

            dispatchEvent(new Event("dateEndChanged"));
            dispatchEvent(new Event("change"));
        }

        //-----------------------------
        // ready
        //-----------------------------
        /**
         * Should return true once the interval has bene fully initialized.
         */
        override public function get ready() : Boolean
        {
            return dateStart != null && dateEnd != null;
        }

        //---------------------------------------------------------------------
        //
        //  Constructor
        //
        //---------------------------------------------------------------------
        /**
         *  Constructor
         */
        public function DateIntervalCollection()
        {
        }

        //---------------------------------------------------------------------
        //
        //  Methods
        //
        //---------------------------------------------------------------------
        override public function getIntervalFor(value : Number) : IInterval
        {
            var date : Date = new Date(value);
            var startOfInterval : Date;
            var endOfInterval : Date;
            switch (intervalType)
            {
                case DateIntervalType.DAY:
                    startOfInterval = new Date(date.fullYear, date.month, date.date);
                    endOfInterval = new Date(date.fullYear, date.month, date.date + (intervalTypeCount - 1), 23, 59, 59, 999);
                    break;
                case DateIntervalType.MONTH:
                    startOfInterval = new Date(date.fullYear, date.month, 1);
                    endOfInterval = new Date(date.fullYear, date.month + (intervalTypeCount - 1), daysInMonth(date.month, date.fullYear), 23, 59, 59, 999);
                    break;
                case DateIntervalType.YEAR:
                    startOfInterval = new Date(date.fullYear, 0, 1);
                    endOfInterval = new Date(date.fullYear + (intervalTypeCount - 1), 11, 31, 23, 59, 59, 999);
                    break;
                default:
                    throw new Error("Invalid intervalType.");
            }

            return new Interval(startOfInterval.time, endOfInterval.time);
        }

        override public function getIntervalsFor(startValue : Number, endValue : Number) : Array
        {
            if (endValue < startValue)
            {
                throw new Error("An error occurred retrieving the intervals. The endValue was less than the startValue.");
            }

            var val : Number = startValue;
            var ret : Array = [];

            while (val <= endValue)
            {
                var interval : IInterval = getIntervalFor(val);
                ret.push(interval);
                val = interval.end + 1;
            }

            return ret;
        }

        //---------------------------------------------------------------------
        //
        //  Date Utility
        //
        //---------------------------------------------------------------------
        //-----------------------------
        //  Date Calculation
        //-----------------------------
        /**
         * Returns the number of days in the month of the date provided.
         */
        protected function daysInMonth(month : int, fullYear : int) : int
        {
            return [
                /** JAN **/31,
                /** FEB **/isLeapYear(fullYear) ? 29 : 28,
                /** MAR **/31,
                /** APR **/30,
                /** MAY **/31,
                /** JUN **/30,
                /** JUL **/31,
                /** AUG **/31,
                /** SEP **/30,
                /** OCT **/31,
                /** NOV **/30,
                /** DEC **/31][month];
        }

        /**
         * Returns true if the year provided is a leap year.
         */
        protected function isLeapYear(fullYear : int) : Boolean
        {
            return (fullYear % 400 == 0) ? true : ((fullYear % 100 == 0) ? false : (fullYear % 4 == 0 ? true : false));
        }
    }
}
